import 'dart:async';
import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:imclient/imclient.dart';
import 'package:sph_driver/AppConfig/Config.dart';
import 'package:sph_driver/Main/CustomerService/VerifyPhoneUserID.dart';

import '../../AppConfig/CustomButton.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/StringEncapsulation.dart';
import '../../http/api.dart';
import '../../http/getapi.dart';
import '../../l10n/messages.dart';
import 'ChangNewPhoneNumber.dart';

class ModifyPhoneNumber extends StatefulWidget {
  const ModifyPhoneNumber({super.key, required this.phoneNum, required this.userMap});
  final String phoneNum;
  final Map userMap;
  @override
  State<ModifyPhoneNumber> createState() => _ModifyPhoneNumberState();
}

class _ModifyPhoneNumberState extends State<ModifyPhoneNumber> {
  late Timer _timer;
  int curentTimer=0;
  bool isTimerRunning = false;
  String smsCode="";
  String validCodeReqNo="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer.cancel();

  }
  void startTimer() {
    setState(() {
      curentTimer = 60;
      isTimerRunning = true; // 设置定时器正在运行
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        curentTimer--;
        if (curentTimer == 0) {
          _timer.cancel();
          isTimerRunning = false; // 定时器结束后设置为非运行状态
          print("Timer ended");

          if (mounted) {
            setState(() {}); // 刷新状态以使按钮可点击
          }
        }
        if (!mounted) {
          _timer.cancel(); // 防止在组件被销毁后仍然运行定时器
        }
        setState(() {});
      });
    });
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        backgroundColor:Colors.white,
        centerTitle: true,
        title: Text("修改手机号",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: ListView(
        children: [
          Container(
            margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
            padding: EdgeInsets.only(bottom: 24.h),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child:Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: 50.h,),
                Text(maskPhoneNumber(widget.phoneNum),style: TextStyle(color: Colors.black,fontSize: 26.sp,fontWeight: FontWeight.w600),),
                TextButton(onPressed: (){
                  if (widget.userMap['personalInfo']!=null){
                    Navigator.push( context, FadeRoute(page:VerifyPhoneUserID()));
                  }else{
                    BrnToast.show("该账号暂未实名认证", context, );
                  }
                }, child: Text("该手机号已不再使用？",style: TextStyle(color: MyColors.themeColor),)),
                SizedBox(height: 50.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text("*",style: TextStyle(color: MyColors.themeColor),),
                    Text("验证码",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                    SizedBox(width: 4.w,),
                    Container(
                      decoration: BoxDecoration(
                        color: MyColors.backgreyColor,
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                      height: 35.h,
                      width: 220.w,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            width: 110.w,
                            height: 35.h,
                            child:  TextField(
                              decoration: InputDecoration(
                                hintText: '必填，请输入',
                                hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                                filled: true,
                                fillColor: MyColors.backgreyColor,
                                border: InputBorder.none,
                                alignLabelWithHint: true,
                                // contentPadding: EdgeInsets.only(bottom: 7.h),
                              ),
                              keyboardType: TextInputType.number,
                              textAlign: TextAlign.left,
                              style: TextStyle(color: Colors.black),
                              onChanged: (value) {
                                setState(() {
                                  smsCode=value;
                                  print(value);
                                });
                              },
                            ),
                          ),
                          TextButton(onPressed: (){
                            if(curentTimer==0) {
                              startTimer();
                              if (isTimerRunning){
                                ApiManager.postData(
                                  context,
                                  'api/auth/sms/sendPhoneValidCode',
                                  {
                                    "phone":widget.phoneNum,
                                    "codeType":"CHANGE_MOBILE_OLD",
                                    "clientType":"DRIVER"
                                  },
                                      (responseData) async {
                                        BrnToast.show("验证码发送成功", context, duration: BrnDuration.short,);
                                        validCodeReqNo=responseData['data']['validCodeReqNo'];

                                  },
                                );

                              }
                            }

                          }, child: curentTimer > 0?Text(curentTimer.toString() +"s重新获取",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),)
                          :Text("获取验证码",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),)),
                        ],
                      ),
                    ),

                  ],
                )
              ],
            ),
          ),
          SizedBox(height:50.h ,),
          Container(
            padding: EdgeInsets.only(left: 20.w,right: 20.w),
            child:
          CustomButton(
              enabled:smsCode.length==4?true:false,
              height: 40.h,
              borderRadius: 30,
              text: '验证并继续',
              normalColor: smsCode.length==4?MyColors.themeColor: MyColors.clickColor,
              pressedColor: Colors.white,
              customOnPressed: () {
                if(smsCode!=""){
                  ApiManager.postData(
                    context,
                    'api/auth/sms/checkPhoneValidCode',
                    {
                      "phone": widget.phoneNum,
                      "validCode":smsCode,
                      "codeType":"CHANGE_MOBILE_OLD",
                      "validCodeReqNo":validCodeReqNo,
                      "clientType": "DRIVER",
                    },
                        (responseData) async {

                      Navigator.push( context, FadeRoute(page:ChangNewPhoneNumber()));


                    },
                  );


                }else{
                  BrnToast.show("请输入验证码", context, duration: BrnDuration.short,);
                }
              }
          ),
          ),
        ],

      ),
    );
  }
}
